package com.cctc.framework.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

public abstract class PaginationController extends BaseController
{
    public static final int DEFAULT_PAGE_SIZE = 10;
    public static final String PAGE_NUMBER = "pageNumber";
    public static final String PAGE_COUNT = "pageCount";
    public static final String ITEM_COUNT = "itemCount";
    public static final String PAGE_SIZE = "pageSize";
    public static final String ORIGINAL_SERVLET_PATH = "ORIGINAL_SERVLET_PATH";
    
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        int itemCount = getItemCount(request, response);
        int pageSize = getPageSize();
        int pageCount = itemCount / pageSize + (itemCount % pageSize == 0 ? 0 : 1);
        int pageNumber = getPageNumber(request);
        if (pageNumber > pageCount)
        {
            pageNumber = pageCount;
        }
        request.setAttribute("pageNumber", Integer.valueOf(pageNumber));
        request.setAttribute("pageCount", Integer.valueOf(pageCount));
        request.setAttribute("itemCount", Integer.valueOf(itemCount));
        request.setAttribute("pageSize", Integer.valueOf(pageSize));
        return executePaginationController(request, response, pageNumber, pageSize);
    }
    
    protected int getPageNumber(HttpServletRequest request)
    {
        Object value = request.getAttribute("pageNumber");
        if (value == null)
        {
            value = request.getParameter("pageNumber");
        }
        if ((value instanceof String))
        {
            return Integer.parseInt((String) value);
        }
        if ((value instanceof Integer))
        {
            return ((Integer) value).intValue();
        }
        
        return 0;
    }
    
    private int getPageSize()
    {
        return DEFAULT_PAGE_SIZE;
    }
    
    protected abstract int getItemCount(HttpServletRequest paramHttpServletRequest,
            HttpServletResponse paramHttpServletResponse) throws Exception;
    
    protected abstract ModelAndView executePaginationController(HttpServletRequest paramHttpServletRequest,
            HttpServletResponse paramHttpServletResponse, int paramInt1, int paramInt2) throws Exception;
}
